python字典创建、访问、添加、删除、遍历、嵌套

您所在的位置:网站首页 Python 字典的操作 python字典创建、访问、添加、删除、遍历、嵌套

python字典创建、访问、添加、删除、遍历、嵌套

2024-07-17 00:10| 来源: 网络整理| 查看: 265

python笔记 使用字典建立一个新字典访问字典中的值添加键值对定义一个空字典修改字典中的值删除键值对 遍历字典遍历所有键值对遍历字典中的所有键遍历字典中的所有值 嵌套在列表中嵌套字典在字典中存储列表在字典中嵌套字典

使用字典

字典是python内置的数据结构之一,是个可变长序列(可以进行增删改操作),放在大括号内,是无序的。

建立一个新字典 alien_0 = {'color':'green','points':5}

在python中,字典是一系列键值对。每一个键都和一个值相关联。键值对之间用逗号分隔,键与值之间用冒号分隔。与键相关联的值可以是数,字典,字符串还有列表。

访问字典中的值 alien_0 = {'color':'green','points':5} print(alien_0['color']) new_points = alien_0['points'] print(f'you just earned {new_points} points')

output:

green you just earned 5 points

另外一种访问方式用get(),与上面访问方式的区别是上面如果指定的键不存在会报错,而使用get()会返回一个默认值。 get()函数有两个参数,第一个参数用于指定键,是必不可少的;第二个参数为指定的键不存在时要返回的值,是可选的。

alien = {'color':'green','points':5} speed = alien.get('speed','No speed value assigned') print(speed) No speed value assigned

如果没有指定get()函数第二个参数,在键不存在时会返回None

添加键值对 alien_0 = {'color':'green','points':5} print(alien_0) alien_0['x_pisition'] = 0 alien_0['y_position'] = 25 print(alien_0)

output:

{'color': 'green', 'points': 5} {'color': 'green', 'points': 5, 'x_pisition': 0, 'y_position': 25} 定义一个空字典 alien_0 = {} print(alien_0) alien_0['color'] = 'green' alien_0['points'] = 5 print(alien_0)

output:

{} {'color': 'green', 'points': 5} 修改字典中的值 alien_0 = {'color':'green','points':5} print(f"The alien is {alien_0['color']}") alien_0['color'] = 'yellow' print(f"The alien is {alien_0['color']}")

output:

The alien is green The alien is yellow

一开始把第二行的引号使用出错,注意在有多个引号时的使用

alien_0 = {'color':'green','points':5} print(f‘The alien is {alien_0['color']}’)

output:

File "", line 2 print(f‘The alien is {alien_0['color']}’) ^ SyntaxError: invalid character in identifier 删除键值对

使用del函数,可以删除指定键及其相关联的值,指明字典名和需要删除的键。

alien_0 = {'color':'green','points':5} print(alien_0) del alien_0['points'] print(alien_0)

output:

{'color': 'green', 'points': 5} {'color': 'green'} 遍历字典 遍历所有键值对 user_0 = { 'username':'efermi', 'first':'enrico', 'last':'fermi', } for key,value in user_0.items(): print(f"\nkey:{key}") print(f"\nvalue:{value}")

output:

key:username value:efermi key:first value:enrico key:last value:fermi

注意:在for循环中,key和value这两个变量名可以更改,但items不可更改,注意拼写。

遍历字典中的所有键 favourite_languages = { 'jen': 'python', 'sarah':'c', 'edward':'ruby', 'phil':'python', } for name in favourite_languages.keys(): print(name.title())

output:

Jen Sarah Edward Phil

访问所有的键用key()函数,name.title()是将所有的name首字母大写输出。 练习:

favourite_languages = { 'jen': 'python', 'sarah':'c', 'edward':'ruby', 'phil':'python', } friends = ['phil','sarah'] for name in favourite_languages.keys(): print(f'Hi,{name.title()}') if name in friends: language = favourite_languages[name].title() print(f"\t {name.title()},I see you love {language}!")

output:

Hi,Jen Hi,Sarah Sarah,I see you love C! Hi,Edward Hi,Phil Phil,I see you love Python! 遍历字典中的所有值

用value()函数

favourite_language = { 'jen':'python', 'sarah':'c', 'edward':'ruby', 'phil':'python', } print('The following languages have been mentioned ') for language in favourite_language.values(): print(language.title())

output:

The following languages have been mentioned Python C Ruby Python

可以发现此时输出项中有重复的,可以使用set函数,得到独一无二的元素。 修改代码为:

for name in set(favourite_language.values()):

output:

The following languages have been mentioned Python Ruby C 嵌套 在列表中嵌套字典 alien_0 = {'color':'green','points':5} alien_1 = {'color':'red','points':10} alien_2 = {'color':'yellow','points':15} alien = [alien_0,alien_1,alien_2] print(alien)

output:

[{'color': 'green', 'points': 5}, {'color': 'red', 'points': 10}, {'color': 'yellow', 'points': 15}] 在字典中存储列表

当需要在一个键关联多个值时,都可以使用在字典中嵌套一个列表。

pizza = { 'crust':'thick', 'toppings':['mushrooms','extra cheese'],# 在字典中嵌套了列表 } print(f"You have ordered a {pizza['crust']}-crust pizza,with the following toppings:") for topping in pizza['toppings']: print(topping)

output:

You have ordered a thick-crust pizza,with the following toppings: mushrooms extra cheese 在字典中嵌套字典 users = { 'aeinstein':{ 'first':'albert', 'last':'einstein', 'location':'princeton', }, 'mcurie':{ 'first':'marie', 'last':'curie', 'location':'paris', }, } for username,user_info in users.items(): print(f'\nUsername:{username}') full_name = f"{user_info['first']} {user_info['last']}" location = user_info['location'] print(f"Full name:{full_name.title()}") print(f"Location:{location.title()}")

output:

Username:aeinstein Full name:Albert Einstein Location:Princeton Username:mcurie Full name:Marie Curie Location:Paris


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3